<template>
  <CommonPage show-footer title="检测记录">
    <NCard>
      <CrudTable
        ref="$table"
        v-model:query-items="queryItems"
        :columns="columns"
        :get-data="api.getDetectionList"
      >
        <template #queryBar>
          <NGrid :cols="4" :x-gap="24">
            <NGi>
              <NFormItem label="检测类型" label-placement="left">
                <NSelect
                  v-model:value="queryItems.detection_type"
                  :options="detectionTypeOptions"
                  clearable
                  placeholder="请选择检测类型"
                />
              </NFormItem>
            </NGi>
            
            <NGi>
              <NFormItem label="检测人员" label-placement="left">
                <NSelect
                  v-model:value="queryItems.operator_id" 
                  :options="operatorOptions"
                  clearable
                  placeholder="请选择检测人员"
                />
              </NFormItem>
            </NGi>

            <NGi span="2">
              <NFormItem label="检测时间" label-placement="left">
                <NDatePicker
                  v-model:value="dateRange"
                  type="datetimerange"
                  clearable
                  :shortcuts="dateShortcuts"
                  style="width: 100%"
                  @update:value="handleDateRangeChange"
                />
              </NFormItem>
            </NGi>
          </NGrid>
        </template>
      </CrudTable>

      <!-- 图片预览模态框 -->
      <NModal
        v-model:show="showImagePreview"
        preset="card"
        style="width: 90vw; max-width: 1200px"
        title="图片预览"
        :bordered="false"
        size="huge"
      >
        <!-- 添加分页控件 -->
        <NPagination
          v-model:page="currentPage"
          :page-size="pageSize"
          :item-count="selectedImages.length"
          show-quick-jumper
          style="margin-bottom: 16px"
        />
        
        <NGrid :cols="3" :x-gap="12" :y-gap="8">
          <NGi v-for="(image, index) in displayImages" :key="index">
            <NImage
              :src="image"
              object-fit="contain"
              :preview-src="image"
              style="width: 100%; height: 240px; object-fit: contain; max-width: 360px; max-height: 240px;"
              :preview-disabled="false"
              :preview-container="null"
              :preview-list="selectedImages"
              :preview-index="getPreviewIndex(index)"
              :img-props="{
                style: 'max-width: 100%; max-height: 100%; object-fit: contain;'
              }"
            />
          </NGi>
        </NGrid>
        
        <!-- 底部分页 -->
        <template #footer>
          <NPagination
            v-model:page="currentPage"
            :page-size="pageSize"
            :item-count="selectedImages.length"
            show-quick-jumper
          />
        </template>
      </NModal>

      <!-- 视频播放模态框 -->
      <NModal
        v-model:show="showVideoPlayer"
        preset="card"
        style="width: 90vw; max-width: 1200px"
        title="视频回放"
        :bordered="false"
        size="huge"
      >
        <div style="display: flex; justify-content: center; align-items: center;">
          <video
            ref="videoPlayer"
            :src="currentVideo"
            controls
            style="width: 100%; height: auto; max-height: 80vh; object-fit: contain;"
            @error="handleVideoError"
          />
        </div>
      </NModal>
    </NCard>
  </CommonPage>
</template>

<script setup>
import { ref, onMounted, h, watch, computed } from 'vue'
import { NButton, NCard, NModal, NGrid, NGi, NImage, NSelect, NDatePicker, NTag, NSpace, NFormItem, NPagination } from 'naive-ui'
import api from '@/api/detection'
import { formatDate } from '@/utils'
import { convertFileSrc } from '@tauri-apps/api/core'

const $table = ref(null)
const queryItems = ref({})
const dateRange = ref(null)
const showImagePreview = ref(false)
const showVideoPlayer = ref(false)
const selectedImages = ref([])
const currentVideo = ref('')
const videoPlayer = ref(null)

// 检测类型选项
const detectionTypeOptions = [
  { label: '平稳性检测', value: 0 },
  { label: '俯仰检测', value: 1 },
  { label: '偏航检测', value: 2 },
  { label: '横滚检测', value: 3 }
]

// 操作员选项 - 需要从用户API获取
const operatorOptions = ref([])

// 日期快捷选项
const dateShortcuts = {
  今天: () => {
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const end = new Date()
    end.setHours(23, 59, 59, 999)
    return [today, end]
  },
  最近7天: () => {
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
    return [start, end]
  }
}

// 处理日期范围变化
const handleDateRangeChange = (value) => {
  if (value) {
    queryItems.value.start_time = formatDate(value[0], 'YYYY-MM-DD HH:mm:ss')
    queryItems.value.end_time = formatDate(value[1], 'YYYY-MM-DD HH:mm:ss')
  } else {
    queryItems.value.start_time = null
    queryItems.value.end_time = null
  }
}

// 表格列配置
const columns = [
  {
    title: '检测类型',
    key: 'detection_type',
    align: 'center',
    render(row) {
      const type = detectionTypeOptions.find(t => t.value === Number(row.detection_type))
      return type ? type.label : '未知'
    }
  },
  {
    title: '检测人员',
    key: 'operator_id',
    align: 'center',
    render(row) {
      const operator = operatorOptions.value.find(op => op.value === Number(row.operator_id))
      return operator ? operator.label : '-'
    }
  },
  {
    title: '检测时间',
    key: 'detection_time',
    align: 'center',
    render(row) {
      return formatDate(row.detection_time, 'YYYY-MM-DD HH:mm:ss')
    }
  },
  {
    title: '检测时长',
    key: 'duration',
    align: 'center',
    render(row) {
      return row.duration ? `${row.duration}秒` : '-'
    }
  },
  {
    title: '状态',
    key: 'status',
    align: 'center',
    render(row) {
      return h(
        NTag,
        {
          type: row.status === 1 ? 'success' : 'warning'
        },
        { default: () => row.status === 1 ? '已完成' : '进行中' }
      )
    }
  },
  {
    title: '操作',
    key: 'actions',
    align: 'center',
    render(row) {
      return h(
        NSpace,
        { justify: 'center' },
        {
          default: () => [
            h(
              NButton,
              {
                size: 'small',
                type: 'primary',
                style: 'margin-right: 8px;',
                disabled: !row.image_path || row.image_path.length === 0,
                onClick: () => handleViewImages(row)
              },
              { default: () => '图片' }
            ),
            h(
              NButton,
              {
                size: 'small',
                type: 'info',
                disabled: !row.video_path,
                onClick: () => handlePlayVideo(row)
              },
              { default: () => '视频' }
            )
          ]
        }
      )
    }
  }
]

// 分页相关
const currentPage = ref(1)
const pageSize = ref(9) // 每页显示9张图片

// 计算当前页显示的图片
const displayImages = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return selectedImages.value.slice(start, end)
})

// 获取预览索引（用于大图预览时的索引）
const getPreviewIndex = (index) => {
  return (currentPage.value - 1) * pageSize.value + index
}

// 查看图片
const handleViewImages = async (row) => {
  try {
    const res = await api.getDetectionImages(row.id)
    if (res.data && Array.isArray(res.data) && res.data.length > 0) {
      selectedImages.value = res.data.map(path => {
        const normalizedPath = path.replace(/\\/g, '/')
        return convertFileSrc(normalizedPath)
      })
      currentPage.value = 1 // 重置页码
      showImagePreview.value = true
    } else {
      window.$message.warning('暂无图片')
    }
  } catch (error) {
    window.$message.error('获取图片失败')
    console.error('获取图片错误:', error)
  }
}

// 播放视频
const handlePlayVideo = async (row) => {
  try {
    const res = await api.getDetectionVideo(row.id)
    if (res.data) {
      const normalizedPath = res.data.replace(/\\/g, '/')
      currentVideo.value = convertFileSrc(normalizedPath)
      showVideoPlayer.value = true
      
      // 重置视频播放器状态
      if (videoPlayer.value) {
        videoPlayer.value.load()
      }
    } else {
      window.$message.warning('暂无视频')
    }
  } catch (error) {
    console.error('视频播放错误:', error)
    window.$message.error('视频加载失败')
  }
}

// 添加视频错误处理
const handleVideoError = (error) => {
  // 只在视频模态框显示时才提示错误
  if (showVideoPlayer.value) {
    console.error('视频加载错误:', error)
    window.$message.error('视频加载失败，请检查视频文件是否存在')
  }
}

// 监听模态框关闭，清理视频
watch(showVideoPlayer, (newVal) => {
  if (!newVal && videoPlayer.value) {
    // 在关闭前先暂停视频播放
    try {
      videoPlayer.value.pause()
      videoPlayer.value.currentTime = 0
    } catch (error) {
      console.warn('重置视频状态失败:', error)
    }
    // 延迟清空视频源
    setTimeout(() => {
      currentVideo.value = ''
    }, 100)
  }
})

// 获取操作员列表
const getOperators = async () => {
  try {
    const res = await api.getOperatorList()
    operatorOptions.value = res.data.map(item => ({
      label: item.username,
      value: item.id
    }))
  } catch (error) {
    window.$message.error('获取操作员列表失败')
  }

}

// 添加重置功能
const handleReset = () => {
  queryItems.value = {}
  dateRange.value = null
  $table.value?.handleSearch()
}

// 监听查询条件变化
watch(
  () => [
    queryItems.value.detection_type,
    queryItems.value.operator_id,
    queryItems.value.start_time,
    queryItems.value.end_time
  ],
  () => {
    $table.value?.handleSearch()
  }
)

onMounted(async () => {
  await getOperators()
  $table.value?.handleSearch()
})
</script>

<style scoped>
.n-modal {
  max-height: 90vh;
  overflow-y: auto;
}

:deep(.n-form-item .n-form-item-label) {
  width: 80px;
}

:deep(.n-card-header) {
  padding-bottom: 0;
}

/* 添加图片预览相关样式 */
:deep(.n-image) {
  transition: transform 0.3s;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 4px;
  overflow: hidden;
}

:deep(.n-image img) {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

:deep(.n-image:hover) {
  transform: scale(1.05);
}

:deep(.n-image-preview-container) {
  z-index: 9999;
}

:deep(.n-image-preview__toolbar) {
  background-color: rgba(0, 0, 0, 0.5);
}

/* 添加视频相关样式 */
:deep(video) {
  background-color: #000;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.n-modal) {
  display: flex;
  flex-direction: column;
}

:deep(.n-modal-body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  max-height: calc(90vh - 120px);
  overflow-y: auto;
}
</style> 